<template>
  <div class="game-container">
    <div class="game-header">
      <button class="back-button" @click="goBack" tabindex="0" ref="backButton">返回</button>
      <h1 class="game-title">你画我猜</h1>
    </div>

    <!-- 连接状态显示 -->
    <div v-if="connectionStatus !== 'connected'" class="connection-status">
      <div v-if="connectionStatus === 'disconnected'" class="connection-panel">
        <h2>启动游戏服务器</h2>
        <div class="loading-spinner"></div>
        <p>正在初始化游戏服务器...</p>
      </div>
      <div v-else-if="connectionStatus === 'waiting'" class="connection-panel">
        <h2>等待设备连接</h2>
        <div class="qrcode-container">
          <img v-if="qrcodeUrl" :src="qrcodeUrl" alt="扫描二维码连接" />
          <div v-else class="qrcode-placeholder">
            <div class="qrcode-loading">生成二维码中...</div>
          </div>
          <p>使用手机/平板扫描二维码连接</p>
        </div>
        <div class="server-info">
          <p>服务器地址: {{ serverUrl }}</p>
          <p>端口: {{ serverPort }}</p>
          <p v-if="roomId">房间ID: {{ roomId }}</p>
        </div>
      </div>
      <div v-else-if="connectionStatus === 'connecting'" class="connection-panel">
        <h2>设备连接中...</h2>
        <div class="loading-spinner"></div>
      </div>
    </div>
    
    <!-- 已连接 - 游戏内容 -->
    <div v-if="connectionStatus === 'connected'" class="game-content">
      <div class="draw-guess-card">
        <div class="game-layout">
          <!-- 侧边信息栏 -->
          <div class="sidebar-info">
            <div class="game-info">
              <div class="round-info">
                <span class="round-label">回合:</span>
                <span class="round-value">{{ currentRound }}/{{ totalRounds }}</span>
              </div>
            </div>
            
            <div class="device-info">
              <div v-if="drawingDeviceId && connectedDeviceNames[drawingDeviceId]" class="connected-device">
                当前连接设备: {{ connectedDeviceNames[drawingDeviceId] }}
                <span v-if="deviceModels[drawingDeviceId]" class="device-model">
                  ({{ deviceModels[drawingDeviceId] }})
                </span>
              </div>
            </div>
          </div>
          
          <!-- 居中画布 -->
          <div class="canvas-container">
            <canvas 
              ref="canvas" 
              class="drawing-canvas"
            ></canvas>
          </div>
        </div>
        
        <!-- TV端不需要猜测功能，只显示绘画 -->
        
        <div class="result-message" v-if="showResult">
          <div v-if="guessedCorrectly" class="correct-message">
            猜对了! 答案是: {{ currentWord }}
          </div>
          <div v-else class="incorrect-message">
            回合结束! 正确答案是: {{ currentWord }}
          </div>
          
          <button 
            class="next-round-btn" 
            @click="nextRound"
            tabindex="0"
            ref="nextRoundButton"
          >
            {{ currentRound < totalRounds ? '下一回合' : '结束游戏' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed } from 'vue';
import { useRouter } from 'vue-router';
import * as QRCode from 'qrcode';

const router = useRouter();
const backButton = ref<HTMLElement | null>(null);

// 网络连接状态
const connectionStatus = ref<'disconnected' | 'connecting' | 'connected' | 'waiting'>('disconnected');
const serverUrl = ref('');
const serverPort = ref(0);
const qrcodeUrl = ref('');
// const socket = ref<WebSocket | null>(null); // 暂时注释掉未使用的变量
const connectedDevices = ref<string[]>([]);
// const isHost = ref(true); // 是否为电视主机 // 暂时注释掉未使用的变量
const drawingDeviceId = ref(''); // 当前绘画设备的ID
const connectedDeviceNames = ref<{[deviceId: string]: string}>({}); // 设备ID到设备名称的映射
const deviceModels = ref<{[deviceId: string]: string}>({}); // 设备ID到设备型号的映射





/**
 * 使用 local_ip_address crate 获取局域网 IP 地址
 * 注意：仅在 Tauri 环境中有效
 */
const getIPViaWebRTC = async (): Promise<string | null> => {
  try {
    const { invoke } = await import('@tauri-apps/api/core');
    const ip = await invoke('get_local_ip') as string;
    return ip || null;
  } catch (e) {
    console.warn('获取本地IP失败:', e);
    return null;
  }
};

/**
 * 获取本地IP地址
 */
const getLocalIP = async (): Promise<string> => {
  // 检查是否在Tauri环境中
  if (typeof window !== 'undefined' && (window as any).__TAURI__) {
    try {
      // 使用Tauri的get_local_ip命令获取IP
      const { invoke } = await import('@tauri-apps/api/core');
      const ip = await invoke('get_local_ip') as string;
      if (ip) {
        console.log('通过Tauri API获取到IP:', ip);
        return ip;
      }
    } catch (e) {
      console.warn('Tauri获取IP失败:', e);
    }
  }
  
  // 优先从当前页面的hostname获取
  if (window.location.hostname && window.location.hostname !== 'localhost') {
    return window.location.hostname;
  }
  
  // 尝试通过WebRTC获取
  try {
    const ip = await getIPViaWebRTC();
    if (ip) return ip;
  } catch (e) {
    console.warn('WebRTC获取IP失败:', e);
  }
  
  throw new Error('无法获取本地IP地址');
};

// 初始化连接和二维码
/**
 * 初始化电视端与WebSocket服务器的连接，并准备二维码显示。
 * 注意：不在此处将连接状态置为 connected，而是在移动端真正接入后再置为 connected，
 * 以便保持“等待设备连接”的界面直至扫码设备加入。
 */
const initConnection = async () => {
  try {
    connectionStatus.value = 'connecting';
    
    // 使用前端方法获取本地IP地址
    const localIP = await getLocalIP();
    serverUrl.value = localIP;
    serverPort.value = 3032;  // 修正为实际的WebSocket服务器端口
    
    console.log('获取到局域网IP:', localIP);
    
    // 连接到WebSocket服务器（注册为电视端）
    await startWebSocketServer();
    
    // 添加连接状态检查
    let retryCount = 0;
    const maxRetries = 5;
    
    while (connectionStatus.value === 'connecting' && retryCount < maxRetries) {
      await new Promise(resolve => setTimeout(resolve, 1000));
      retryCount++;
    }
    
    if (connectionStatus.value === 'connecting') {
      throw new Error('连接超时，请检查服务器是否运行');
    }
  } catch (error) {
    console.error('Failed to initialize connection:', error);
    connectionStatus.value = 'disconnected';
    // 提供手动输入IP的选项
    showConnectionError('无法获取IP地址，游戏无法启动');
  }
};



/**
 * 生成房间ID
 */
const generateRoomId = (): string => {
  return Math.random().toString(36).substring(2, 8).toUpperCase();
};

/**
 * 显示连接错误信息
 */
const showConnectionError = (message: string) => {
  serverUrl.value = '连接失败';
  qrcodeUrl.value = '';
  alert(message);
};



// WebSocket连接实例
let wsConnection: WebSocket | null = null;

// 连接到WebSocket服务器（电视端作为客户端连接到独立的WebSocket服务器）
/**
 * 启动WebSocket服务器（TV端作为服务器）
 * TV端启动自己的WebSocket服务器，等待手机端连接
 * 根据项目规则，禁止使用HTTP服务器，仅使用WebSocket
 */
const startWebSocketServer = async () => {
  console.log(`启动WebSocket服务器在端口 ${serverPort.value}`);
  
  try {
    // 检查是否在Tauri环境中
    if (typeof window !== 'undefined' && (window as any).__TAURI__) {
      // 使用Tauri命令启动WebSocket服务器
      const { invoke } = await import('@tauri-apps/api/core');
      const result = await invoke('start_websocket_server', { port: serverPort.value }) as string;
      console.log('WebSocket服务器启动结果:', result);
      
      // 等待服务器启动完成
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 验证服务器URL和端口
      if (!serverUrl.value || !serverPort.value) {
        throw new Error('服务器URL或端口未设置');
      }
      
      // 连接到自己的WebSocket服务器进行TV端注册
      const wsUrl = `ws://${serverUrl.value}:${serverPort.value}`;
      console.log('Tauri环境：连接到WebSocket服务器:', wsUrl);
      
      try {
        wsConnection = new WebSocket(wsUrl);
      } catch (error) {
        console.error('创建WebSocket连接失败:', error);
        throw new Error(`无法创建WebSocket连接: ${error}`);
      }
      
      wsConnection.onopen = () => {
        console.log('Tauri环境：WebSocket连接已建立');
        
        // 注册为电视端
        const registerMessage = {
          type: 'register_tv',
          deviceId: 'tv-' + Date.now(),
          timestamp: Date.now()
        };
        
        console.log('Tauri环境：发送注册消息:', registerMessage);
        try {
          wsConnection?.send(JSON.stringify(registerMessage));
          console.log('Tauri环境：注册消息已发送');
        } catch (error) {
          console.error('Tauri环境：发送注册消息失败:', error);
        }
      };
      
      wsConnection.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          console.log('Tauri环境：收到WebSocket消息:', data);
          handleSocketMessage(data);
        } catch (error) {
          console.error('Tauri环境：解析WebSocket消息失败:', error);
        }
      };
      
      wsConnection.onclose = (event) => {
        console.log('Tauri环境：WebSocket连接已关闭', event.code, event.reason);
        wsConnection = null;
      };
      
      wsConnection.onerror = (error) => {
        console.error('Tauri环境：WebSocket连接错误:', error);
        wsConnection = null;
        
        // 提供更详细的错误信息
        let errorMessage = 'WebSocket连接失败';
        if (error instanceof Event && error.target) {
          const ws = error.target as WebSocket;
          if (ws.readyState === WebSocket.CLOSED) {
            errorMessage = `无法连接到WebSocket服务器 ${wsUrl}，请检查服务器是否正在运行`;
          }
        }
        
        console.error(errorMessage);
        connectionStatus.value = 'disconnected';
      };
      
    } else {
      // 在浏览器开发环境中，模拟服务器启动过程
      console.log('浏览器开发模式：模拟WebSocket服务器启动');
      
      // 生成房间ID
      roomId.value = generateRoomId();
      
      // 生成二维码URL（手机端连接地址）
      // 在开发模式下，手机端页面通过HTTP服务器访问，WebSocket连接使用8080端口
      const connectionUrl = `http://${serverUrl.value}:3030/#/drawguess?roomId=${roomId.value}&ip=${serverUrl.value}&port=8080`;
      qrcodeUrl.value = await QRCode.toDataURL(connectionUrl);
      
      // 设置连接状态为等待连接
      connectionStatus.value = 'waiting';
      
      console.log('开发模式：二维码已生成，等待设备连接');
      console.log('连接URL:', connectionUrl);
      
      // 在开发模式下，不尝试连接WebSocket服务器
      // 只生成二维码供扫描连接
      console.log('开发模式：仅显示二维码，等待真实设备连接');
    }
    
  } catch (error) {
    console.error('启动WebSocket服务器失败:', error);
    connectionStatus.value = 'disconnected';
    
    // 显示更详细的错误信息
    const errorMessage = error instanceof Error ? error.message : '未知错误';
    alert(`无法启动WebSocket服务器\n错误: ${errorMessage}\n请检查端口是否被占用`);
    throw error;
  }
};

// WebSocket连接管理
// const wsConnections = ref<Map<string, any>>(new Map()); // 暂时注释掉未使用的变量

// 向所有连接的设备广播消息
const broadcastToDevices = (message: any) => {
  if (wsConnection && wsConnection.readyState === WebSocket.OPEN) {
    const messageToSend = {
      ...message,
      timestamp: Date.now()
    };
    
    console.log('广播消息到所有设备:', messageToSend);
    wsConnection.send(JSON.stringify(messageToSend));
  } else {
    console.error('WebSocket连接未建立，无法发送消息');
  }
};



// 房间ID
const roomId = ref<string>('');

/**
 * 处理来自服务器的消息（电视端）
 * - tv_registered: 保存房间ID并生成带 roomId 与 ip 的二维码
 * - device_connected/mobile_connected: 切换为 connected 并向服务器发送 start_game，让服务器广播绘制词语
 * - draw_data/guess_submitted: 处理绘制与猜测
 */
const handleSocketMessage = async (data: any) => {
  switch (data.type) {
    case 'tv_registered': {
      // 电视端注册成功，保存房间ID
      roomId.value = data.roomId;
      console.log('电视端注册成功，房间ID:', data.roomId);
      
      // 生成WebSocket连接信息和网页URL
      const wsInfo = {
        type: 'connect_mobile',
        url: `ws://${serverUrl.value}:3032`,
        roomId: data.roomId,
        webUrl: `http://${serverUrl.value}:3030/#/drawguess?roomId=${data.roomId}&ip=${serverUrl.value}&port=3032`
      };
      
      // 生成二维码图片（data URL）
      try {
        // 同时包含WebSocket连接信息和网页URL
        qrcodeUrl.value = await QRCode.toDataURL(wsInfo.webUrl);
        console.log('二维码已生成');
        console.log('连接信息:', wsInfo);
        
        // 设置连接状态为等待连接
        connectionStatus.value = 'waiting';
      } catch (e) {
        console.error('二维码生成失败:', e);
        qrcodeUrl.value = '';
      }
      break;
    }
    
    case 'device_connecting':
      // 设备开始连接
      connectionStatus.value = 'connecting';
      break;
      
    case 'device_connected':
      if (!connectedDevices.value.includes(data.deviceId)) {
        connectedDevices.value.push(data.deviceId);
      }
      // 保存设备名称
      if (data.deviceName) {
        connectedDeviceNames.value[data.deviceId] = data.deviceName;
      }
      // 保存设备型号
      if (data.deviceModel) {
        deviceModels.value[data.deviceId] = data.deviceModel;
      } else {
        // 请求设备发送型号信息
        broadcastToDevices({ 
          type: 'request_device_info',
          targetDeviceId: data.deviceId
        });
      }
      connectionStatus.value = 'connected';
      drawingDeviceId.value = data.deviceId;
      // 确保有词语后再广播
      if (!currentWord.value) {
        currentWord.value = wordList[Math.floor(Math.random() * wordList.length)];
      }
      console.log('设备连接成功，广播词语:', currentWord.value);
      broadcastToDevices({ type: 'start_game', word: currentWord.value });
      break;
    
    case 'mobile_connecting':
      // 手机端开始连接
      connectionStatus.value = 'connecting';
      
      // 向移动端发送连接成功确认消息
      if (wsConnection && wsConnection.readyState === WebSocket.OPEN) {
        wsConnection.send(JSON.stringify({
          type: 'mobile_connected',
          deviceId: data.deviceId || 'mobile',
          deviceName: data.deviceName || '移动设备',
          timestamp: Date.now()
        }));
        console.log('已向移动端发送连接成功确认');
        
        // 设置电视端连接状态为已连接
        connectionStatus.value = 'connected';
        drawingDeviceId.value = data.deviceId || 'mobile';
        
        // 保存设备名称
        if (data.deviceName) {
          connectedDeviceNames.value[data.deviceId || 'mobile'] = data.deviceName;
        }
        
        // 确保有词语后再广播
        if (!currentWord.value) {
          currentWord.value = wordList[Math.floor(Math.random() * wordList.length)];
        }
        console.log('手机端连接成功，广播词语:', currentWord.value);
        broadcastToDevices({ type: 'start_game', word: currentWord.value });
      }
      break;
    
    case 'request_word':
      // 处理移动端请求词语
      console.log('收到移动端词语请求');
      if (!currentWord.value) {
        currentWord.value = wordList[Math.floor(Math.random() * wordList.length)];
      }
      console.log('广播词语到移动端:', currentWord.value);
      broadcastToDevices({ type: 'start_game', word: currentWord.value });
      break;
    
    case 'word_received':
      // 处理移动端收到词语的确认
      console.log('移动端已收到词语:', data.word);
      break;
    
    case 'mobile_disconnected':
      // 处理移动端断开连接
      console.log('移动端已断开连接');
      connectionStatus.value = 'disconnected';
      drawingDeviceId.value = '';
      break;
    
    case 'ping':
      // 处理心跳包，回复pong
      if (wsConnection && wsConnection.readyState === WebSocket.OPEN) {
        wsConnection.send(JSON.stringify({ type: 'pong', timestamp: Date.now() }));
        console.log('收到ping，回复pong');
      }
      break;
    
    case 'draw_data':
      // 处理来自设备的绘画数据
      if (ctx.value && canvas.value) {
        // 将相对坐标转换为TV端画布的绝对坐标
        const convertToAbsoluteCoordinates = (relativeX: number, relativeY: number) => {
          return {
            x: relativeX * canvas.value!.width,
            y: relativeY * canvas.value!.height
          };
        };
        
        // 获取绝对坐标
        let absolutePos = { x: 0, y: 0 };
        
        if (data.relativeX !== undefined && data.relativeY !== undefined) {
          absolutePos = convertToAbsoluteCoordinates(data.relativeX, data.relativeY);
        } else if (data.x !== undefined && data.y !== undefined) {
          // 兼容旧格式
          absolutePos = { x: data.x, y: data.y };
        }
        

        // 设置绘图样式
        ctx.value.strokeStyle = data.isEraser ? '#FFFFFF' : data.color;
        ctx.value.lineWidth = data.size;
        ctx.value.lineCap = 'round';
        ctx.value.lineJoin = 'round';
        ctx.value.globalCompositeOperation = data.isEraser ? 'destination-out' : 'source-over';
        
        // 处理绘制开始
        if (data.drawType === 'draw_start') {
          // 开始新的绘制路径
          ctx.value.beginPath();
          ctx.value.moveTo(absolutePos.x, absolutePos.y);
          isCurrentlyDrawing.value = true;
          lastX.value = absolutePos.x;
          lastY.value = absolutePos.y;
          console.log('TV端绘图开始 - 相对坐标:', data.relativeX, data.relativeY, '- 绝对坐标:', absolutePos.x, absolutePos.y);
        } else if (data.drawType === 'draw_end') {
          // 结束绘制 - 完成当前路径
          if (isCurrentlyDrawing.value) {
            // 画最后一段到结束点
            ctx.value.lineTo(absolutePos.x, absolutePos.y);
            ctx.value.stroke();
          }
          isCurrentlyDrawing.value = false;
          lastX.value = 0;
          lastY.value = 0;
          console.log('TV端绘图结束');
        } else if (data.drawType === 'draw_move' && isCurrentlyDrawing.value) {
          // 继续绘制路径 - 连续绘制线条
          // 直接画线到当前点，不需要重新开始路径
          ctx.value.lineTo(absolutePos.x, absolutePos.y);
          ctx.value.stroke();
          
          // 更新最后位置
          lastX.value = absolutePos.x;
          lastY.value = absolutePos.y;
        }
      }
      break;
    
    case 'guess_submitted':
      // TV端不处理猜测，只由手机端处理
      break;
      
    case 'image_data':
      // 处理来自移动端的图像数据
      if (ctx.value && canvas.value) {
        const img = new Image();
        img.onload = () => {
          ctx.value?.clearRect(0, 0, canvas.value!.width, canvas.value!.height);
          ctx.value?.drawImage(img, 0, 0, canvas.value!.width, canvas.value!.height);
        };
        img.src = data.data;
      }
      break;
      
    case 'clear_canvas':
      // 处理来自移动端的清除画布消息
      console.log('收到清除画布消息，准备清除画布...');
      if (canvas.value && ctx.value) {
        console.log('画布尺寸:', canvas.value.width, 'x', canvas.value.height);
        
        // 使用clearRect清除画布内容
        ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height);
        
        // 重新设置白色背景
        ctx.value.fillStyle = '#FFFFFF';
        ctx.value.fillRect(0, 0, canvas.value.width, canvas.value.height);
        
        console.log('TV端画布已清除并重置背景');
      } else {
        console.error('画布或上下文不存在，无法清除画布');
        console.log('canvas:', canvas.value);
        console.log('ctx:', ctx.value);
      }
      break;
      
    case 'emoji_data':
      // 处理来自移动端的表情数据
      if (ctx.value && canvas.value) {
        // 将相对坐标转换为TV端画布的绝对坐标
        const absoluteX = data.relativeX * canvas.value.width;
        const absoluteY = data.relativeY * canvas.value.height;
        
        // 根据TV端画布大小调整字体大小
        const scaledFontSize = Math.min(canvas.value.width, canvas.value.height) * 0.1;
        
        // 设置字体样式
        ctx.value.font = `${scaledFontSize}px Arial`;
        ctx.value.textAlign = 'center';
        ctx.value.textBaseline = 'middle';
        ctx.value.fillStyle = '#000000';
        
        // 绘制表情
        ctx.value.fillText(data.emoji, absoluteX, absoluteY);
        
        console.log('TV端表情已绘制:', data.emoji, '位置:', absoluteX, absoluteY);
      }
      break;
      
    case 'device_info':
      // 处理设备信息响应
      if (data.deviceId && data.deviceModel) {
        deviceModels.value[data.deviceId] = data.deviceModel;
        console.log(`收到设备 ${data.deviceId} 的型号信息:`, data.deviceModel);
      }
      break;
  }
};





// 清空所有设备的画布
const clearAllDevices = () => {
  console.log('执行clearAllDevices函数，广播清除画布消息...');
  broadcastToDevices({
    type: 'clear_canvas',
    timestamp: Date.now() // 添加时间戳确保消息唯一性
  });
  console.log('清除画布消息已广播');
};
const canvas = ref<HTMLCanvasElement | null>(null);
const colorOptions = ref<HTMLElement[]>([]);
const smallBrush = ref<HTMLElement | null>(null);
const mediumBrush = ref<HTMLElement | null>(null);
const largeBrush = ref<HTMLElement | null>(null);
const clearButton = ref<HTMLElement | null>(null);
const guessInputEl = ref<HTMLInputElement | null>(null);
const submitButton = ref<HTMLElement | null>(null);
const nextRoundButton = ref<HTMLElement | null>(null);

// 游戏状态
const currentRound = ref(1);
const totalRounds = ref(5);
// 移除未使用的 score 变量

// 动态类绑定
// const containerClass = computed(() => {
//   return {
//     'game-container': true
//   };
// });
// 移除倒计时相关变量
const isDrawing = ref(true); // true: 画图者, false: 猜词者
const showResult = ref(false);
const guessedCorrectly = ref(false);

// 绘图状态
const lastX = ref(0);
const lastY = ref(0);
const isCurrentlyDrawing = ref(false);

// TV端不需要猜测功能

// 词库
const wordList = [
  '苹果', '香蕉', '太阳', '月亮', '星星',
  '汽车', '飞机', '火车', '轮船', '自行车',
  '猫', '狗', '老虎', '大象', '长颈鹿',
  '电视', '电脑', '手机', '冰箱', '洗衣机',
  '足球', '篮球', '棒球', '网球', '乒乓球'
];
// 初始化时就选择一个词语
const currentWord = ref(wordList[Math.floor(Math.random() * wordList.length)]);

// 绘图相关变量
const colors = ['#000000', '#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF'];
const currentColor = ref('#000000');
const brushSize = ref(10);

/**
 * 选择颜色
 */
const selectColor = (color: string) => {
  currentColor.value = color;
};

/**
 * 选择笔刷大小
 */
const selectBrushSize = (size: number) => {
  brushSize.value = size;
};

/**
 * 提交猜测（TV端不需要此功能，但为了避免引用错误保留空实现）
 */
const submitGuess = () => {
  // TV端不处理猜测
  console.log('TV端不支持猜测功能');
};

// 计算属性
const ctx = computed(() => {
  if (canvas.value) {
    return canvas.value.getContext('2d');
  }
  return null;
});

/**
 * 初始化游戏
 */
const initGame = () => {
  // 随机选择一个词
  currentWord.value = wordList[Math.floor(Math.random() * wordList.length)];
  console.log('初始化游戏，当前词语:', currentWord.value);
  
  // 重置游戏状态
  isDrawing.value = true; // 第一回合默认为画图者
  showResult.value = false;
  guessedCorrectly.value = false;
  
  // 清空画布
  clearCanvas();
  
  // 发送新词给已连接的手机端
  if (connectionStatus.value === 'connected') {
    console.log('广播新词语到手机端:', currentWord.value);
    broadcastToDevices({ type: 'start_game', word: currentWord.value });
  }
};

// 移除计时器函数



// 下一回合
const nextRound = () => {
  if (currentRound.value < totalRounds.value) {
    currentRound.value++;
    // 切换角色
    isDrawing.value = !isDrawing.value;
    // 初始化新回合
    initGame();
    
    // 根据角色聚焦到不同元素
    setTimeout(() => {
      if (isDrawing.value) {
        // 画图者聚焦到颜色选择
        colorOptions.value[0]?.focus();
      } else {
        // 猜词者聚焦到输入框
        guessInputEl.value?.focus();
      }
    }, 100);
  } else {
    // 游戏结束，返回主页
    goBack();
  }
};

// TV端不需要猜测功能，移除submitGuess函数

// TV端不需要绘图功能，只保留接收手机端绘图数据的功能

/**
 * 清空画布
 */
const clearCanvas = () => {
  console.log('执行clearCanvas函数...');
  if (!canvas.value || !ctx.value) {
    console.error('画布或上下文不存在，无法清除画布');
    console.log('canvas:', canvas.value);
    console.log('ctx:', ctx.value);
    return;
  }
  
  // 清空本地画布 - 使用clearRect而不是fillRect
  console.log('清除本地画布，尺寸:', canvas.value.width, 'x', canvas.value.height);
  ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height);
  
  // 设置白色背景
  ctx.value.fillStyle = '#FFFFFF';
  ctx.value.fillRect(0, 0, canvas.value.width, canvas.value.height);
  console.log('本地画布已清除并设置白色背景');
  
  // 通知所有连接的设备清空画布
  console.log('通知所有设备清空画布');
  clearAllDevices();
};

// 返回主页
const goBack = () => {
  router.push('/');
};

// 键盘导航处理
const handleKeyDown = (event: KeyboardEvent) => {
  if (showResult.value) {
    // 结果显示时，只处理Enter键
    if (event.key === 'Enter' && document.activeElement === nextRoundButton.value) {
      nextRound();
    }
    return;
  }
  
  switch (event.key) {
    case 'ArrowUp':
    case 'ArrowDown':
    case 'ArrowLeft':
    case 'ArrowRight':
      navigateFocus(event.key.replace('Arrow', '').toLowerCase() as 'up' | 'down' | 'left' | 'right');
      break;
    case 'Enter':
      handleEnterKey();
      break;
  }
};

// 处理Enter键
const handleEnterKey = () => {
  const activeElement = document.activeElement;
  
  if (activeElement === backButton.value) {
    goBack();
  } else if (colorOptions.value.includes(activeElement as HTMLElement)) {
    const index = colorOptions.value.findIndex(el => el === activeElement);
    selectColor(colors[index]);
  } else if (activeElement === smallBrush.value) {
    selectBrushSize(5);
  } else if (activeElement === mediumBrush.value) {
    selectBrushSize(10);
  } else if (activeElement === largeBrush.value) {
    selectBrushSize(15);
  } else if (activeElement === clearButton.value) {
    clearCanvas();
  } else if (activeElement === submitButton.value) {
    submitGuess();
  }
};

// 焦点导航
const navigateFocus = (direction: 'up' | 'down' | 'left' | 'right') => {
  const activeElement = document.activeElement;
  
  // 画图者的导航逻辑
  if (isDrawing.value) {
    if (colorOptions.value.includes(activeElement as HTMLElement)) {
      const currentIndex = colorOptions.value.findIndex(el => el === activeElement);
      
      if (direction === 'down') {
        // 从颜色选择向下导航到笔刷大小
        if (brushSize.value === 5) {
          smallBrush.value?.focus();
        } else if (brushSize.value === 10) {
          mediumBrush.value?.focus();
        } else {
          largeBrush.value?.focus();
        }
      } else if (direction === 'left' && currentIndex > 0) {
        colorOptions.value[currentIndex - 1]?.focus();
      } else if (direction === 'right' && currentIndex < colorOptions.value.length - 1) {
        colorOptions.value[currentIndex + 1]?.focus();
      } else if (direction === 'up') {
        backButton.value?.focus();
      }
    } else if ([smallBrush.value, mediumBrush.value, largeBrush.value].includes(activeElement as HTMLElement)) {
      if (direction === 'up') {
        // 从笔刷大小向上导航到颜色选择
        const colorIndex = colors.findIndex(c => c === currentColor.value);
        colorOptions.value[colorIndex !== -1 ? colorIndex : 0]?.focus();
      } else if (direction === 'down') {
        // 从笔刷大小向下导航到清空按钮
        clearButton.value?.focus();
      } else if (direction === 'left') {
        if (activeElement === mediumBrush.value) {
          smallBrush.value?.focus();
        } else if (activeElement === largeBrush.value) {
          mediumBrush.value?.focus();
        }
      } else if (direction === 'right') {
        if (activeElement === smallBrush.value) {
          mediumBrush.value?.focus();
        } else if (activeElement === mediumBrush.value) {
          largeBrush.value?.focus();
        }
      }
    } else if (activeElement === clearButton.value) {
      if (direction === 'up') {
        // 从清空按钮向上导航到笔刷大小
        if (brushSize.value === 5) {
          smallBrush.value?.focus();
        } else if (brushSize.value === 10) {
          mediumBrush.value?.focus();
        } else {
          largeBrush.value?.focus();
        }
      }
    } else if (activeElement === backButton.value && direction === 'down') {
      // 从返回按钮向下导航到颜色选择
      colorOptions.value[0]?.focus();
    }
  } 
  // 猜词者的导航逻辑
  else {
    if (activeElement === guessInputEl.value) {
      if (direction === 'right') {
        submitButton.value?.focus();
      } else if (direction === 'up') {
        backButton.value?.focus();
      }
    } else if (activeElement === submitButton.value) {
      if (direction === 'left') {
        guessInputEl.value?.focus();
      } else if (direction === 'up') {
        backButton.value?.focus();
      }
    } else if (activeElement === backButton.value && direction === 'down') {
      guessInputEl.value?.focus();
    }
  }
};

/**
 * 初始化画布尺寸 - 正方形画布，尺寸为屏幕高度的2/3
 */
const initCanvasSize = () => {
  if (!canvas.value) return;
  
  // 获取屏幕尺寸
  const screenHeight = window.innerHeight;
  const screenWidth = window.innerWidth;
  
  // 计算目标画布尺寸：屏幕高度的2/3
  const targetSize = Math.floor(screenHeight * 2 / 3);
  
  // 确保画布不超出屏幕宽度，并保持正方形
  const maxWidth = screenWidth * 0.9; // 留出10%的边距
  const canvasSize = Math.min(targetSize, maxWidth);
  
  // 设置最小尺寸确保清晰度
  const finalSize = Math.max(canvasSize, 600);
  
  canvas.value.width = finalSize;
  canvas.value.height = finalSize;
  
  console.log('TV端大尺寸正方形画布:', canvas.value.width, 'x', canvas.value.height);
  console.log('屏幕尺寸:', screenWidth, 'x', screenHeight);
  console.log('目标尺寸(屏幕高度2/3):', targetSize);
  
  // 重新设置白色背景
  if (ctx.value) {
    ctx.value.fillStyle = '#FFFFFF';
    ctx.value.fillRect(0, 0, canvas.value.width, canvas.value.height);
  }
};

/**
 * 处理窗口大小变化
 */
const handleResize = () => {
  // 延迟执行以确保DOM更新完成
  setTimeout(() => {
    initCanvasSize();
  }, 100);
};

onMounted(async () => {
  // 设置画布大小 - 优化TV端显示
  if (canvas.value) {
    initCanvasSize();
    // 初始化白色背景
    clearCanvas();
  }
  
  // 添加键盘事件监听
  window.addEventListener('keydown', handleKeyDown);
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize);
  
  // 初始化连接和二维码（等待 tv_registered 后生成二维码）
  await initConnection();
  
  // 初始化游戏
  initGame();
  
  // 初始聚焦
  if (isDrawing.value) {
    colorOptions.value[0]?.focus();
  } else {
    guessInputEl.value?.focus();
  }
});

onBeforeUnmount(() => {
  // 移除键盘事件监听
  window.removeEventListener('keydown', handleKeyDown);
  
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize);
  
  // 清理连接状态
  connectionStatus.value = 'disconnected';
  connectedDevices.value = [];
  
  // 通知手机端断开连接
  broadcastToDevices({
    type: 'tv_disconnected'
  });
});
</script>

<style scoped lang="scss">
@use '../assets/styles/drawguess.scss';

</style>
